<template>
  <div v-if="!item.hidden">
    <!-- 有子菜单的情况 -->
    <el-sub-menu
      v-if="hasChildren"
      :index="item.id"
      :popper-append-to-body="true"
    >
      <template #title>
        <el-icon v-if="item.icon">
          <component :is="item.icon" />
        </el-icon>
        <span>{{ item.title }}</span>
      </template>
      
      <sidebar-item
        v-for="child in item.children"
        :key="child.id"
        :item="child"
        :base-path="resolvePath(child.path)"
      />
    </el-sub-menu>

    <!-- 没有子菜单的情况 -->
    <el-menu-item
      v-else
      :index="resolvePath(item.path)"
    >
      <el-icon v-if="item.icon">
        <component :is="item.icon" />
      </el-icon>
      <template #title>
        <span>{{ item.title }}</span>
      </template>
    </el-menu-item>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { MenuItem } from '@/config/menu'
import path from 'path-browserify'

interface Props {
  item: MenuItem
  basePath?: string
}

const props = withDefaults(defineProps<Props>(), {
  basePath: ''
})

// 是否有子菜单
const hasChildren = computed(() => {
  return item.value.children && item.value.children.length > 0
})

// 当前菜单项
const item = computed(() => props.item)

// 解析路径
const resolvePath = (routePath?: string) => {
  if (!routePath) return ''
  
  if (isExternal(routePath)) {
    return routePath
  }
  
  if (isExternal(props.basePath)) {
    return props.basePath
  }
  
  return path.resolve(props.basePath, routePath)
}

// 判断是否为外部链接
const isExternal = (path: string) => {
  return /^(https?:|mailto:|tel:)/.test(path)
}
</script>

<style scoped>
.el-menu-item,
.el-sub-menu__title {
  height: 50px;
  line-height: 50px;
}

.el-menu-item.is-active {
  background-color: var(--el-color-primary-light-9) !important;
  color: var(--el-color-primary) !important;
}

.el-menu-item:hover,
.el-sub-menu__title:hover {
  background-color: var(--el-color-primary-light-9) !important;
}

.el-icon {
  margin-right: 8px;
  width: 16px;
  height: 16px;
}
</style>
